package com.lczyfz.campusinfo.modules.alipay.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.lczyfz.campusinfo.common.config.Global;
import com.lczyfz.campusinfo.common.enums.OrderType;
import com.lczyfz.campusinfo.common.web.BaseController;
import com.lczyfz.campusinfo.modules.alipay.config.AlipayConfig;
import com.lczyfz.campusinfo.modules.campusinfoeducation.entity.CampusinfoAbroad;
import com.lczyfz.campusinfo.modules.campusinfoeducation.entity.CampusinfoPubmed;
import com.lczyfz.campusinfo.modules.campusinfoeducation.service.CampusinfoAbroadService;
import com.lczyfz.campusinfo.modules.campusinfoeducation.service.CampusinfoPubmedService;
import com.lczyfz.campusinfo.modules.campusinfoexam.entity.CampusinfoExam;
import com.lczyfz.campusinfo.modules.campusinfoexam.entity.CampusinfoServant;
import com.lczyfz.campusinfo.modules.campusinfoexam.entity.CampusinfoTrain;
import com.lczyfz.campusinfo.modules.campusinfoexam.service.CampusinfoExamService;
import com.lczyfz.campusinfo.modules.campusinfoexam.service.CampusinfoServantService;
import com.lczyfz.campusinfo.modules.campusinfoexam.service.CampusinfoTrainService;
import com.lczyfz.campusinfo.modules.campusinfopay.entity.CampusinfoPay;
import com.lczyfz.campusinfo.modules.campusinfopay.service.CampusinfoPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lczyfz.campusinfo.common.enums.CampusinfoOrderStat;
import com.lczyfz.campusinfo.common.enums.PayType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *创建人:陈文
 *创建时间:2017年8月15日 下午4:35:54
 *备注:
 */
@Controller
@RequestMapping(value = "alipay")
public class AlipayH5Controller extends BaseController{
	//服务器异步通知
	@Autowired
	private CampusinfoPayService campusinfoPayService;
	@Autowired
	private CampusinfoAbroadService campusinfoAbroadService; //出国
	@Autowired
	private CampusinfoPubmedService campusinfoPubmedService;//考研
	@Autowired
	private CampusinfoServantService campusinfoServantService;//公务员
	@Autowired
	private CampusinfoExamService campusinfoExamService; //模拟
	@Autowired
	private CampusinfoTrainService campusinfoTrainService; //考证
	@RequestMapping(value ="authRedirect")
	public void authRedirect(HttpServletRequest request){
		logger.info("=====authRedirect===");
		Map<String,String> params = new HashMap<String,String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			System.out.println(name+":"+valueStr);
			params.put(name, valueStr);
		}
	}
	//服务器异步通知
	@RequestMapping(value ="gateway")
	public void gateway(HttpServletRequest request){
		logger.info("=====gateway===");
	}
	//生成支付宝订单url
	@RequestMapping(value="pay")
	public void pay(@RequestParam(value="orderNo",required=true)String orderNo,Model model,
			HttpServletResponse  response,HttpServletRequest request) throws ServletException, IOException{
		String ua = request.getHeader("user-agent").toLowerCase();
		if (ua.indexOf("micromessenger") > 0) {
			logger.info("====iswx====");
			request.getRequestDispatcher("/WEB-INF/views/modules/zhifubaopay/pay.jsp").forward(request,response);
		}else{
			logger.info("====nowx=====");
			CampusinfoPay campusinfoPay =campusinfoPayService.get(orderNo);
			if(campusinfoPay.getStat().equals(CampusinfoOrderStat.CLOSE)){
				model.addAttribute("reason","订单已关闭");
				model.addAttribute("isPay", Global.NO);//不允许继续支付
				model.addAttribute("infoNo",campusinfoPay.getId());
			}else if(campusinfoPay.getStat().equals(CampusinfoOrderStat.FAIL)){//支付失败的订单
				Integer count = 1;
				count++;
				String newId=orderNo+"-"+String.valueOf(count);
				payAction(newId, request, response, campusinfoPay);
			}else{//未支付操作的订单
				payAction(orderNo, request, response, campusinfoPay);
			}

		}
	}
//
	public void payAction(String orderNo,HttpServletRequest request,HttpServletResponse  response,
						  CampusinfoPay campusinfoPay){
		// 商户订单号，商户网站订单系统中唯一订单号，必填
		 String out_trade_no = orderNo;
		// 订单名称，必填
	    String subject =  campusinfoPay.getGoodsName();
		System.out.println(subject);
	    // 付款金额，必填
	    String total_amount="0.01";
	    // 商品描述，可空
	    String body = "报名支付";
	    // 超时时间 可空
	    String timeout_express="2m";
	    // 销售产品码 必填
	    String product_code="QUICK_WAP_PAY";
	    //**********************//*
	    // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
	    //调用RSA签名方式
	    AlipayClient client = new DefaultAlipayClient(AlipayConfig.getUrl(), AlipayConfig.getAppId(), AlipayConfig.getRsaPrivateKey(), AlipayConfig.getFormat(), AlipayConfig.getCharset(), AlipayConfig.getAlipayPublicKey(),AlipayConfig.getSigntype());
	    AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

	    // 封装请求支付信息
	    AlipayTradeWapPayModel paymodel=new AlipayTradeWapPayModel();
	    paymodel.setOutTradeNo(out_trade_no);
	    paymodel.setSubject(subject);
	    paymodel.setTotalAmount(total_amount);
	    paymodel.setBody(body);
	    paymodel.setTimeoutExpress(timeout_express);
	    paymodel.setProductCode(product_code);
	    alipay_request.setBizModel(paymodel);
	    // 设置异步通知地址
	    alipay_request.setNotifyUrl(AlipayConfig.getNotifyUrl());
	    // 设置同步地址
	    alipay_request.setReturnUrl(AlipayConfig.getReturnUrl());

	    // form表单生产
	    String form = "";
			// 调用SDK生成表单

		try {
			form = client.pageExecute(alipay_request).getBody();
			response.setContentType("text/html;charset=" + AlipayConfig.getCharset());
			response.getWriter().write(form);
			response.getWriter().flush();
		    response.getWriter().close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="return_url")
	public String return_url(HttpServletRequest request,Model model) throws AlipayApiException {
		logger.info("======return_url====");
		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			System.out.println("name==" + name);

			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
				params.put(name, valueStr);
			}
		}
		//商户订单号
		String outTradeNo = request.getParameter("out_trade_no");
		logger.info("outTradeNo==" + outTradeNo);
		CampusinfoPay campusinfoPay =campusinfoPayService.get(outTradeNo);
		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.getAlipayPublicKey(), AlipayConfig.getCharset(), "RSA2");

		System.out.println("h5 ret ver=" + signVerified);
		if (signVerified) {
			Map<String, Object> payInfo = new HashMap<>();
			payInfo.put("amount",  campusinfoPay.getAmount());
			model.addAttribute("orderNo", outTradeNo);
			model.addAttribute("payInfo", payInfo);
			return "modules/zhifubaopay/success";
		}else {
			model.addAttribute("orderNo",outTradeNo);
			return "modules/zhifubaopay/fail";
		}
	}
	
	@RequestMapping(value="notify_url")
	@ResponseBody
	public String notify_url(HttpServletRequest request) throws AlipayApiException{
		logger.info("======notify_url====");
		Map<String,String> params = new HashMap<String,String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		//商户订单号
		String outTradeNo = request.getParameter("out_trade_no");
		//支付宝交易状态
		String tradeStatus =request.getParameter("trade_status");
		logger.info("tradeStatus=="+tradeStatus);
		//支付宝交易号
		String tradeNo = request.getParameter("trade_no");
		logger.info("tradeNo=="+tradeNo);
		if(StringUtils.isBlank(outTradeNo)){
			return "订单号不能为空";
		}
		String arr[] = outTradeNo.split("-");
		int count = 0;
		if(arr.length>1){
			outTradeNo=arr[0];
			count=Integer.valueOf(arr[1]);
		}
		boolean verifyResult = AlipaySignature.rsaCheckV1(params, AlipayConfig.getAlipayPublicKey(), AlipayConfig.getCharset(), "RSA2");
		System.out.println("h5 verify=="+verifyResult);
		//商户订单号
		if(verifyResult) {//验证成功
			
			if(tradeStatus.equals("TRADE_FINISHED")){
				logger.info("TRADE_FINISHED:"+outTradeNo);
			}else if (tradeStatus.equals("TRADE_SUCCESS")){
				logger.info("TRADE_SUCCESS:"+outTradeNo);
			}
			CampusinfoPay campusinfoPay = new CampusinfoPay();
//			//更新订单状态
			campusinfoPay.setId(outTradeNo);
			campusinfoPay.setPaytype(PayType.ALIPAY.getValue());
     		campusinfoPay.setStat(CampusinfoOrderStat.DONE.getValue());
			campusinfoPay.setCount(count);
			campusinfoPayService.save(campusinfoPay);
			if(outTradeNo.startsWith(OrderType.Servan.getValue())){ //公务员开头
				CampusinfoServant findcampusinfoServant = new CampusinfoServant();
				findcampusinfoServant.setOrderCode(outTradeNo);
				CampusinfoServant campusinfoServant =campusinfoServantService.getOrderCode(findcampusinfoServant);
				campusinfoServant.setStatus(CampusinfoOrderStat.DONE.getValue());
				campusinfoServantService.status(campusinfoServant);
			}else if(outTradeNo.startsWith(OrderType.Train.getValue())) { //考证
				CampusinfoTrain findcampusinfoTrain = new CampusinfoTrain();
				findcampusinfoTrain.setOrderCode(outTradeNo);
				CampusinfoTrain campusinfoTrain = campusinfoTrainService.getOrderCode(findcampusinfoTrain);
				campusinfoTrain.setStatus(CampusinfoOrderStat.DONE.getValue());
				campusinfoTrainService.status(campusinfoTrain);
			} else if(outTradeNo.startsWith(OrderType.Exam.getValue())){ //考试
				CampusinfoExam findcampusinfoExam = new CampusinfoExam();
				findcampusinfoExam.setOrderCode(outTradeNo);
				CampusinfoExam campusinfoExam = campusinfoExamService.getOrderCode(findcampusinfoExam);
				campusinfoExam.setStatus(CampusinfoOrderStat.DONE.getValue());
				campusinfoExamService.status(campusinfoExam);
			} else  if(outTradeNo.startsWith(OrderType.Abroad.getValue())) {//出国{
				CampusinfoAbroad findcampusinfoAbroad = new CampusinfoAbroad();
				findcampusinfoAbroad.setOrderCode(outTradeNo);
				findcampusinfoAbroad.setStatus(CampusinfoOrderStat.DONE.getValue());
				CampusinfoAbroad campusinfoAbroad= campusinfoAbroadService.getOrderCode(findcampusinfoAbroad);
				campusinfoAbroadService.status(campusinfoAbroad);
			} else if(outTradeNo.startsWith(OrderType.Major.getValue())){
				CampusinfoPubmed findcampusinfoPumbe = new CampusinfoPubmed();
				findcampusinfoPumbe.setOrderCode(outTradeNo);
				findcampusinfoPumbe.setStatus(CampusinfoOrderStat.DONE.getValue());
				CampusinfoPubmed campusinfoPubmed = campusinfoPubmedService.getOrderCode(findcampusinfoPumbe);
				campusinfoPubmedService.status(campusinfoPubmed);
			}
//			//记录交易信息
			return "success";
		}else {//验证失败
      		logger.info("验签失败:"+outTradeNo);
			CampusinfoPay campusinfoPay = new CampusinfoPay();
			campusinfoPay.setId(outTradeNo);
			campusinfoPay.setPaytype(PayType.ALIPAY.getValue());
			campusinfoPay.setStat(CampusinfoOrderStat.FAIL.getValue());
			campusinfoPay.setCount(count);
			campusinfoPayService.save(campusinfoPay);
			return "fail";
		}
	}
	
	@RequestMapping(value="orderPay")
	public String inwxPay(@RequestParam(value="orderNo",required=true)String orderNo,
			HttpServletRequest request){
		String ua = request.getHeader("user-agent").toLowerCase();
		System.out.println(ua);
		if (ua.indexOf("micromessenger") > 0) {
			System.out.println("===iswx====");
			return "modules/zhifubaopay/pay";
		}else{
			System.out.println("===nowx====");
			return "modules/zhifubaopay/pay";
		}
	}
}
